Optimize truncateFileTree token estimation and sampling seed - #1216
Optimize truncateFileTree token estimation and sampling seed#1216nordicnode wants to merge 2 commits into
Conversation
|
Nice diagnosis on the seed and However, in the extension list refactor at the bottom of Separately, the Good test additions overall; would like one covering the extension-list edge case before this goes in. |
|
Thanks for the keen eye @codebuff-team! Both points have been addressed in the latest commit:
|
Summary
packages/agent-runtime/src/system-prompt/truncate-file-tree.ts, optimize token counting, sampling seed generation, and unimportant file filtering during prompt file tree truncation.sampleSizeWithSeedwas passedJSON.stringify(sortedFiles) + JSON.stringify(sampleCount)as its seed. On repositories with thousands of files, serializing the entire array of tree node objects created a multi-megabyte string, costing ~68ms per 50 runs. Replaced this with a lightweight deterministic seed (${sortedFiles.length}:${sampleCount}:${sortedFiles[0]?.path ?? ''}:${sortedFiles[sortedFiles.length - 1]?.path ?? ''}) that computes in 0.01ms (over 6,800x faster).countTokensJson(printedTree)withcountTokens(printedTree).printedTreeis directly interpolated into markdown template literals in the system prompt (system-prompt/prompts.ts), never JSON-encoded. CallingcountTokensJsonexecutedJSON.stringify(str)to escape quotes and newlines, unnecessarily inflating token counts and allocating intermediate strings.countTokensdirectly measures the true prompt token cost and runs 3.2x faster (6.71ms vs 21.31ms).unimportantExtensionsintoUNIMPORTANT_DIR_PATTERNSandUNIMPORTANT_EXTENSIONSso directory and file filters do not repeatedly evaluateext.startsWith('/')across 51 items for every single file in the tree..sobinary filtering: Confirmed and restored.soalongside.exe,.dll, and.libinUNIMPORTANT_EXTENSIONS.packages/agent-runtime/src/system-prompt/__tests__/truncate-file-tree.test.tscovering budget thresholds, build directory filtering, depth-based fallback, and compiled binary/shared library (.so,.dll,.exe,.lib) filtering.Test plan
bun test src/system-prompt/__tests__/truncate-file-tree.test.ts(4 passed, 0 failed)bun test src/tools/handlers/__tests__/read-subtree.test.ts(7 passed, 0 failed)bun run build:sdk(successful build)bun freebuff/cli/build.ts 0.0.0-ci(successful binary build)bun cli/scripts/smoke-binary.ts cli/bin/freebuff(OK)bun x prettier --check packages/agent-runtime/src/system-prompt/truncate-file-tree.ts packages/agent-runtime/src/system-prompt/__tests__/truncate-file-tree.test.ts(All matched files use Prettier code style)